package at.gv.bmwf.fons.model.ontology.static_impl;

import at.gv.bmwf.fons.model.ontology.NamedResource;

import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDFS;

public class StaticNamedResource extends StaticResource implements NamedResource {
	private final String name;
	
	protected StaticNamedResource(Resource resource) {
		super(resource);
		this.name = getName();
	}

	@Override
	public String getName() {
		if (name == null) {
			ResultSet result = execSelect(String.format("SELECT ?label WHERE{" +
					"?s <%s> <%s>. ?s <%s> ?label." +
					"FILTER langMatches(lang(?label),\"DE\") }", OWL.sameAs, getResource(), RDFS.label));

			while (result.hasNext()) {
				QuerySolution solution = result.next();
				if (solution.contains("?label")) {
					return solution.getLiteral("?label").getString();
				} else break;
			}
			
			getResource().addLiteral(RDFS.label, getModel().createLiteral(getResource().getLocalName(), "de"));
			return getResource().getLocalName();
		}
		return name;
	}

	@Override
	public String toString() {
		return name;
	}
}
